package com.shuke.medical.insure.billDownload;

import com.shuke.medical.insure.billDownload.WXPayBill;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/***
 * @title WXPayBillUtil
 * @description：创建微信支付对账单接口调用类
 * @author woo hua
 * @version 1.0.0
 * @create 2023/4/13 14:53
 **/
public class WXPayBillUtil {

    /**
     * 获取微信支付对账单并解析
     * @param billDate 对账单日期，格式为yyyyMMdd
     * @param filePath 对账单保存路径
     * @return 解析后的对账单数据
     * @throws Exception
     */
    public static List<WXPayBill> getWXPayBill(String billDate, String filePath) throws Exception {
//        WXPayConfig config = WXPayConfig.getInstance();
//        WXPay wxPay = new WXPay(config);
//
//        Map<String, String> data = new HashMap<>();
//        data.put("bill_date", billDate);
//        data.put("bill_type", "ALL");
//        String responseXml = wxPay.downloadBill(data);

        String responseXml ="";

        // 将对账单写入文件
        File file = new File(filePath);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
        osw.write(responseXml);
        osw.close();

        // 解析对账单
        List<WXPayBill> list = parseWXPayBill(filePath);
        return list;
    }

    /**
     * 解析微信支付对账单
     * @param filePath 对账单文件路径
     * @return 对账单数据列表
     * @throws Exception
     */
    private static List<WXPayBill> parseWXPayBill(String filePath) throws Exception {
        List<WXPayBill> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));

        // 读取文件头
        String header = br.readLine();
        String[] payment = header.split(",");
        // 读取总交易数及总交易额
        String[] total = br.readLine().split(",");
        int totalNum = Integer.parseInt(total[1]);
        double totalFee = Double.parseDouble(total[2]);

        // 跳过分割线
        br.readLine();
        // 读取交易详情
        for (int i = 0; i < totalNum; i++) {
            String[] detail = br.readLine().split(",");
            WXPayBill bill = new WXPayBill(detail[0], detail[1], detail[2], detail[3], detail[4], detail[5], detail[6], detail[7], detail[8], detail[9], detail[10], detail[11], detail[12], detail[13], detail[14], detail[15], detail[16], detail[17], detail[18], detail[19], detail[20], detail[21], detail[22], detail[23]);
            list.add(bill);
        }

        br.close();
        return list;
    }
}
